package ai.mspbots.test;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

import cn.hutool.core.codec.Base64;

public class EncryptUtil {

    private static final String SECRET_KEY = "3333e6e143439161"; // 16 bytes
    private static final String SECRET_IV = "e3bbe7e3ba84431a"; // 16 bytes
    private static final String ALGORITHM = "AES/CBC/PKCS5PADDING";

    // Encrypt the data
    public static String encryptPkcs7(String data) {
        try {
            // Create secret key and IV
            SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(SECRET_IV.getBytes(StandardCharsets.UTF_8));

            // Initialize the cipher for encryption
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);

            // Encrypt the data
            byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));

            // Return the Base64-encoded ciphertext
            return Base64.encode(encrypted);
        } catch (Exception e) {
            System.out.println("e = " + e.getMessage());
        }
        return null;
    }

    // Decrypt the data
    public static String decrypt(String encryptedData) {
        try {
            // Create secret key and IV
            SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(SECRET_IV.getBytes(StandardCharsets.UTF_8));

            // Initialize the cipher for decryption
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

            // Decode the encrypted data from Base64 and decrypt
            byte[] original = cipher.doFinal(Base64.decode(encryptedData));

            // Return the decrypted data as a string
            return new String(original, StandardCharsets.UTF_8);
        } catch (Exception e) {
            System.out.println("e = " + e.getMessage());
        }
        return null;
    }
}
